from django.db import transaction
from django.db.models.signals import post_save
from django.dispatch import receiver

from social.call.models import AVCall
from social.call.tasks import send_call_over_message
from social.rank.tasks import add_av_call_ranked


@receiver(post_save, sender=AVCall)
def post_post_save(sender, instance: AVCall, created, **kwargs):
    update_fields = kwargs.get('update_fields', set())
    if update_fields and 'status' in update_fields:
        if instance.status in [AVCall.OVER, AVCall.ABNORMAL_OVER]:
            transaction.on_commit(lambda: add_av_call_ranked.delay(instance.id))
        if instance.status > AVCall.ING:
            transaction.on_commit(lambda: send_call_over_message.delay(instance.id))
